package sy.service.impl;

import java.util.*;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

import sy.dao.BaseDaoI;
import sy.model.Tmenu;
import sy.pageModel.Menu;
import sy.service.MenuServiceI;

@Service("menuService")
public class MenuServiceImpl implements MenuServiceI {

	@Autowired
	private BaseDaoI<Tmenu> menuDao;
	@Override
	public List<Menu> getTree(String id) {
        List<Menu> list=new ArrayList<Menu>();
        String  hql="";
        if("".equals(id)||null==id||"null".equals(id)){
        	//查询所有根节点
        	hql="from Tmenu t where t.tmenu is null";
        }else {
        	//查询 pid 为id的所有子节点
			hql="from Tmenu t  where t.tmenu.id='"+id+"'";
		}
 		List<Tmenu> l=menuDao.find(hql);
		if(l!=null&&l.size()>0){
			for(int i=0;i<l.size();i++){
				Menu menu=new Menu();
				Tmenu  tmenu=l.get(i);
				BeanUtils.copyProperties(tmenu, menu);
				Map<String,Object> attributes=new HashMap<String, Object>();
 				attributes.put("url", tmenu.getUrl());
				menu.setAttributes(attributes);
				if(tmenu.getTmenus()!=null&&!tmenu.getTmenus().isEmpty()){
					menu.setState("closed");
				}else {
					menu.setState("open");
				}
				menu.setIconCls(tmenu.getIconcls());
				list.add(menu);
			}
		}
		return list;
	}
	@Override
	public List<Menu> getAllTree() {
		  List<Menu> list=new ArrayList<Menu>();
		  List<Tmenu> l=menuDao.find("from Tmenu t");
		  if(l!=null&&l.size()>0){
				for(int i=0;i<l.size();i++){
					Menu menu=new Menu();
					Tmenu  tmenu=l.get(i);
					BeanUtils.copyProperties(tmenu, menu);
					Map<String,Object> attributes=new HashMap<String, Object>();
					attributes.put("url",tmenu.getUrl());
					menu.setAttributes(attributes);
					if(tmenu.getTmenu()!=null){
					     menu.setPid(tmenu.getTmenu().getId());
					}
					menu.setIconCls(tmenu.getIconcls());
					list.add(menu);
				}
			}
	   return list;
	}

}
